<script lang="ts" setup>
  import { computed, onMounted, ref, watch } from 'vue';
  import { GameProductGroup } from '@/types/game';
  import { getGameDetail } from '@/api/game';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps<{
    gameId: string;
    modelValue?: string[];
  }>();

  const emit = defineEmits(['update:modelValue']);

  const parentProductGroups = ref<GameProductGroup[]>([]);

  const initData = async () => {
    try {
      const gameRes = await getGameDetail(props.gameId);
      const gameInfo = gameRes.data.data;
      if (gameInfo.gameProductGroupVOS) {
        gameInfo.gameProductGroupVOS.forEach((group) => {
          group.products = group.products.filter((p) => !p.disabled);
          group.products.forEach((product) => {
            if (product.rmbPrice) {
              product.rmbPrice /= 100;
            }
          });
          group.products.sort((p1, p2) => {
            if (p1.mustPay && !p2.mustPay) {
              return -1;
            }
            if (!p1.mustPay && p2.mustPay) {
              return 1;
            }
            return 0;
          });
        });
      }
      if (gameInfo.parentGame) {
        const parentGameRes = await getGameDetail(gameInfo.parentGame.id);
        const parentGameInfo = parentGameRes.data.data;
        if (parentGameInfo.gameProductGroupVOS) {
          parentGameInfo.gameProductGroupVOS.forEach((group) => {
            group.products = group.products.filter((p) => !p.disabled);
            group.products.forEach((product) => {
              if (product.rmbPrice) {
                product.rmbPrice /= 100;
              }
            });
            group.products.sort((p1, p2) => {
              if (p1.mustPay && !p2.mustPay) {
                return -1;
              }
              if (!p1.mustPay && p2.mustPay) {
                return 1;
              }
              return 0;
            });
          });
        }
        parentProductGroups.value = [
          ...(parentGameInfo.gameProductGroupVOS || []),
          ...(gameInfo.gameProductGroupVOS || []),
        ];
      } else {
        parentProductGroups.value = [...(gameInfo.gameProductGroupVOS || [])];
      }
    } finally {
      // do nothing
    }
  };

  const theParentId = computed(() => {
    return props.gameId;
  });

  const handleProductClicked = (groupIndex: number, productIndex: number) => {
    const group = parentProductGroups.value[groupIndex];
    const product = group.products[productIndex];
    // 必须支付的，跳过
    if (product.mustPay) {
      return;
    }

    let ids = props.modelValue || [];
    const id = product.id as string;

    if (group.minProductChoose === 1 && group.maxProductChoose === 1) {
      if (ids.includes(id)) {
        Message.info(`${group.name}至少要选择一项`);
      } else {
        group.products.forEach((p) => {
          const pId = p.id as string;
          if (!p.mustPay) {
            ids = ids.filter((i) => i !== pId);
          }
        });
        ids.push(id);
        emit('update:modelValue', ids);
      }
    } else if (ids.includes(id)) {
      emit(
        'update:modelValue',
        ids.filter((i) => i !== id)
      );
    } else {
      emit('update:modelValue', [...ids, id]);
    }
  };

  watch(
    [theParentId],
    async () => {
      await initData();
      const ids: string[] = [];
      parentProductGroups.value.forEach((group) => {
        group.products.forEach((p) => {
          if (p.mustPay) {
            ids.push(p.id as string);
          }
        });
      });
      emit('update:modelValue', ids);
    },
    {
      immediate: true,
    }
  );
</script>

<template>
  <div class="product-selector">
    <div
      v-for="(group, groupIndex) in parentProductGroups"
      :key="group.id"
      class="product-group"
    >
      <div class="product-group-name">{{ group.name }}</div>

      <div class="product-list">
        <div
          v-for="(product, productIndex) in group.products"
          :key="product.id"
          class="product"
          @click="handleProductClicked(groupIndex, productIndex)"
        >
          <div v-if="!product.mustPay" class="product-check">
            <a-checkbox
              :model-value="(modelValue || []).includes(product.id as string)"
            />
          </div>

          <div class="product-info">
            <div class="product-name">
              {{ product.name }}
            </div>

            <div v-if="product.description" class="product-desc">
              {{ product.description }}
            </div>
          </div>

          <div class="product-price">
            <span>￥</span>
            {{ product.rmbPrice ? product.rmbPrice.toFixed(2) : '-' }}
          </div>
        </div>
      </div>

      <div v-if="group.description" class="product-group-desc">{{
        group.description
      }}</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .product-selector {
    flex: 1;
  }

  .product {
    &-group {
      margin-bottom: 20px;
      &-name {
        font-weight: 500;
        margin: 0 0 6px 18px;
      }
      &-desc {
        margin: 6px 10px 0 18px;
        font-size: 12px;
        font-weight: 300;
        color: var(--color-text-2);
      }
    }
  }

  .product {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 12px 8px;
    background: rgb(var(--gray-2));
    border-radius: 8px;
    &:last-child {
      margin-bottom: 0;
    }

    &-check {
      height: 14px;
    }

    &-info {
      flex: 1;
      min-width: 0;
      margin: 0 10px;
    }

    &-desc {
      margin-top: 5px;
      color: var(--color-text-2);
      font-size: 12px;
    }

    &-price {
      font-size: 18px;
      color: rgb(var(--green-6));
      margin-right: 8px;
      span {
        font-size: 13px;
        color: var(--color-text-2);
      }
    }
  }
</style>
